import { treeToArray } from '@web-utils/core'
import { isURL } from '@/util/validate'
import { fixPath, iframePath, isFormPath, isNewTabPath, urlToHash } from '@/util/iframe'

export const useNewStyleRoute = true

export function buildRouteNew(menus, outerRouter) {
  const menuProps = {
    label: 'label',
    path: 'path',
    icon: 'icon',
    children: 'children'
  }

  const rootRoute = {
    path: '/',
    component: () => import('@/views/skeleton/Skeleton'),
    children: treeToArray(menus)
      .map(value => toRoute(value, menuProps))
      .filter(value => value)
  }
  outerRouter.addRoute(rootRoute)
}

export function toRoute(menuItem, menuProps) {
  if (menuItem[menuProps.children]?.length > 0 || !menuItem.path || menuItem.path === '/') {
    return null
  }

  if (isURL(menuItem[menuProps.path])) {
    if (!isNewTabPath(menuItem[menuProps.path])) {
      const hash = urlToHash(menuItem[menuProps.path])
      menuItem[menuProps.path] = `/${iframePath}/${hash}`
    }
    return null
  }

  const path = menuItem[menuProps.path].replace(/^\//, '')

  const componentFilePath = fixPath(menuItem.path)

  const name = menuItem[menuProps.label]

  const icon = menuItem[menuProps.icon]

  const meta = { keepAlive: Number(menuItem.keepAlive) === 1, icon, title: name }

  const route = {
    path,
    meta,
    component: () => {
      return import(/* webpackChunkName: "r-" */ `../module/${componentFilePath}.vue`)
    }
  }

  if (isFormPath(path)) {
    route.props = route => {
      return { ...route.query, ...route.params }
    }
  }

  return route
}
